import java.util.ArrayList;
import java.util.List;

public class Solution998 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public TreeNode insertIntoMaxTree(TreeNode root, int val) {
        List<Integer> list=new ArrayList<>();
        dfs(root,list);
        list.add(val);
        return dfs2(list,0,list.size()-1);
    }

    private TreeNode dfs2(List<Integer> list, int a, int b) {
        if (a>b){
            return null;
        }
        int max=-1,pos=-1;
        for (int i=a;i<=b;i++){
            if (list.get(i)>max){
                max=list.get(i);
                pos=i;
            }
        }
        return new TreeNode(max,dfs2(list,a,pos-1),dfs2(list,pos+1,b));
    }

    private void dfs(TreeNode root, List<Integer> list) {
        if (root==null){
            return;
        }
        dfs(root.left,list);
        list.add(root.val);
        dfs(root.right,list);
    }

    public static void main(String[] args) {
        System.out.println(new Solution998().insertIntoMaxTree(new TreeNode(4,new TreeNode(1),new TreeNode(3,new TreeNode(2),null)),5).val);
    }
}
